package com.soms.servlet;

import cn.hutool.json.JSONUtil;
import com.soms.constants.LoginConst;
import com.soms.entity.Role;
import com.soms.entity.User;
import com.soms.service.RoleService;
import com.soms.service.UserService;
import com.soms.service.impl.RoleServiceImpl;
import com.soms.service.impl.UserServiceImpl;
import com.soms.util.HttpResponseUtil;
import com.soms.util.PageInfo;
import com.soms.util.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/server/role")
public class RoleServlet extends HttpServlet {

    private final RoleService roleService = new RoleServiceImpl();

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        String type = req.getParameter("type");
        if (type != null) {
            switch (type) {
                case "queryPage":
                    doQueryPage(req, resp);
                    break;
                case "add":
                    doAddRole(req, resp);
                    break;
                case "queryById":
                    doQueryById(req, resp);
                    break;
                case "edit":
                    doEditRole(req, resp);
                    break;
                case "deleteById":
                    doDeleteById(req, resp);
                    break;
                case "getAll":
                    getAllRole(req, resp);
                    break;
                default:

                    break;
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 根据当前页码、每页的数量、以及有可能的查询条件，获取当前页的表格数据和总数据量、总页数
     *
     * @param req
     * @param resp
     */
    private void doQueryPage(HttpServletRequest req,
                             HttpServletResponse resp) throws IOException {
        // 分页参数
        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");
        // 查询参数
        String roleCode = req.getParameter("roleCode");
        String roleName = req.getParameter("roleName");
        String createdBegin = req.getParameter("createdBegin");
        String createdEnd = req.getParameter("createdEnd");
        // 构建分页对象
        PageInfo<Role> pageInfo = new PageInfo<>();
        pageInfo.setCurrentPage(Integer.parseInt(currentPage));
        pageInfo.setPageSize(Integer.parseInt(pageSize));
        pageInfo.addParam("roleCode", roleCode)
                .addParam("roleName", roleName)
                .addParam("createdBegin", createdBegin)
                .addParam("createdEnd", createdEnd);
        // 查询分页数据
        pageInfo = roleService.queryPage(pageInfo);
        HttpResponseUtil.writeJson(resp,
                JSONUtil.toJsonStr(ResultUtil.success(null, pageInfo)));
    }

    /**
     * 新增一个角色
     *
     * @param req
     * @param resp
     */
    private void doAddRole(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 先判断是否已经登录
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
            return;
        }
        // 获取登录用户的用户编码
        String userCode = session.getAttribute(LoginConst.USER_CODE).toString();
        User loginUser = userService.getUserByUserCode(userCode);
        String roleCode = req.getParameter("roleCode");
        String roleName = req.getParameter("roleName");
        HttpResponseUtil.writeJson(resp, roleService.add(roleCode, roleName, loginUser.getId()));
    }

    /**
     * 通过id查询单个角色
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    private void doQueryById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        HttpResponseUtil.writeJson(resp, roleService.queryById(Integer.parseInt(id)));
    }

    /**
     * 更新一个角色
     *
     * @param req
     * @param resp
     */
    private void doEditRole(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 先判断是否已经登录
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
            return;
        }
        // 获取登录用户的用户编码
        String userCode = session.getAttribute(LoginConst.USER_CODE).toString();
        User loginUser = userService.getUserByUserCode(userCode);
        String id = req.getParameter("id");
        String roleCode = req.getParameter("roleCode");
        String roleName = req.getParameter("roleName");
        HttpResponseUtil.writeJson(resp,
                roleService.update(Integer.parseInt(id), roleCode, roleName, loginUser.getId()));
    }

    /**
     * 通过id删除单个角色
     *
     * @param req
     * @param resp
     */
    private void doDeleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        HttpResponseUtil.writeJson(resp,
                roleService.deleteById(Integer.parseInt(id)));
    }

    /**
     * 获取所有的角色
     *
     * @param req
     * @param resp
     */
    private void getAllRole(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(roleService.getAllRole()));
    }
}
